<template>
  <el-container class="container">
      <el-header>
          <el-alert title="任意用户名和密码可登录" type="warning"></el-alert>
      </el-header>
      <el-main>
          <el-form>
              <el-form-item label="用户名">
                  <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item label="密码"> 
                  <el-input v-model="form.password" placeholder="请输入密码" show-password></el-input>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" @click="submit" >{{loginName}}</el-button>
              </el-form-item>
          </el-form>
      </el-main>
  </el-container>
</template>

<script>
import {login,getUserInfo} from '@/api'

export default {
  name:'LoginView',
  data() {
    return { 
        form:{
            username:'',
            password:''
        },
        logining:0
    }
  },
  computed:{
      loginName(){
          return this.logining===0?'登录':'登录中...'
      }
  },
  methods: {
    submit(){
        if(!this.form.username || !this.form.password){
            this.$message({
                showClose: false,
                message: '请输入用户名或密码',
                type: 'error'
            });
        }

        this.logining = 1;
        login(this.form).then(async response =>{
            const {status,token,message} = response;
            if(!status){
                this.$message.error('登录失败，请确认用户名和密码');
            }

            if(status){
                localStorage.setItem('token',token);

                try {
                    //异步=》同步
                    const userinfo =  await getUserInfo();
 
                    //保存用户信息到Store中
                    this.$store.commit('setUserInfo',userinfo);
                    //跳转到重定向页面
                    const {redirectUrl} = this.$route.query;
                    this.$router.push(redirectUrl || '/');
                } catch (error) {
                    console.log(error);
                    this.$message.error(error);
                }
            }
            this.logining = 0;
        });
    }
  }
}
</script>

<style lang="scss">
    .container{
        width: 400px;
        margin: 0 auto;
    }

    .el-button{
        width: 100%;
    }
</style>